package org.amn.file;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.util.Assert;

/**
 * <p>
 * 描述:文件和目录工具类
 * </p>
 *
 * @see
 * @author yangjun1120@gmail.com
 *
 */
abstract public class FileUtils {
    private final static String NAME_SEP = "_";

    private final static SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHH");

    /**
     * 
     * <p>
     * 描述:获取  xxx_n.txt 格式
     * </p>
     * @param
     * @return
     * @throws
     * @see
     * @since %I%
     */
    public static String formatFileName(String name) {
        Assert.notNull(name, "fileName must not be null");
        StringBuffer sb = new StringBuffer();
        int parseInt = 1;
        String tName = null;

        String posfix = "";

        int idx = name.indexOf(".");

        tName = name;

        if (idx > -1) {
            posfix = (idx + 1) == name.length() ? "" : name.substring(idx + 1);
            tName = name.substring(0, idx);
        }

        if (name.indexOf(NAME_SEP) > -1) { //+1
            String[] split = tName.split(NAME_SEP);

            Assert.isTrue((split != null && split.length == 2), "filename pattern is error:" + name);
            tName = split[0];
            String tIndex = split[1];

            parseInt = Integer.parseInt(tIndex);
            parseInt++;

        }

        if (idx > -1)
            return sb.append(tName).append(NAME_SEP).append(parseInt).append(".").append(posfix).toString();
        else
            return sb.append(tName).append(NAME_SEP).append(parseInt).toString();
    }

    public static boolean renameTo(File f, String dest) {
        Assert.notNull(f, "file must not be null");
        Assert.notNull(dest, "destination path is not null");
        File nf = new File(dest);

        File parent = new File(nf.getParent());

        if (!parent.exists()) {
            parent.mkdirs();
        }

        boolean flag = f.renameTo(nf);

        if (flag) {
            nf.setLastModified(System.currentTimeMillis());
        }

        return flag;

    }

    /**
     * 
     * <p>
     * 描述:删除文件和目录
     * </p>
     * @param
     * @return 如果删除成功，返回true，如果删除失败或传入的文件、目录是空，则返回false
     * @throws
     * @see
     * @since %I%
     */
    public static boolean deleteFile(File f) {

        if (f != null) {
            return f.delete();
        }

        return false;
    }

    public static File[] listDir(String path) {
        Assert.notNull(path, "path must not be null");
        File f = new File(path);
        return f.listFiles();
    }

    public static String[] listDirFilePath(String path) {
        File d = new File(path);
        File[] listFiles = d.listFiles();
        String[] newList = new String[listFiles == null ? 0 : listFiles.length];
        if (listFiles != null && listFiles.length > 0) {

            for (int i = 0; i < listFiles.length; i++) {
                newList[i] = listFiles[i].getAbsolutePath();
            }
        }
        return newList;
    }

    public static String formatPath(String p) {
        Assert.notNull(p, "path must not be null");
        File f = new File(p);
        return f.getAbsolutePath();
    }

    /**
     * 
     * <p>
     * 描述:统计某个目录下的的文件夹和目录个数
     * </p>
     * @param
     * @return
     * @throws
     * @see
     * @since %I%
     */
    public static int getDirFileCount(String path) {
        Assert.notNull(path, "path must not be null");
        File f = new File(path);

        if (f.isFile()) {
            return 1;
        } else if (f.isDirectory()) {
            return f.list().length;
        }

        return 0;
    }

    private static File createFile(String name) throws IOException {
        Assert.notNull(name, "name  must not be null");

        File f = new File(name);

        f.createNewFile();

        return f;
    }

    public static void writeToFile(String fileName, byte[] bytes) throws IOException {
        File oFile = createFile(fileName);
        FileOutputStream fos = new FileOutputStream(oFile);

        FileChannel f2 = fos.getChannel();

        ByteBuffer buf = ByteBuffer.wrap(bytes);

        buf.flip();
        f2.write(buf);
        buf.clear();

        f2.close();

        //        long len = 0;
        //        while ((len = f.read(buf)) != -1) {
        //            buf.flip();
        //            f2.write(buf);
        //            buf.clear();
        //        }
        //
        //        f2.close();
        //        f.close();

    }

    public static String getFolder() {
        return sdf.format(new Date());
    }

    public static void main(String[] args) throws Exception {
        //        File f = new File("D:/work/j2eeproject/filemsgtrans/tmp/queue/2011032816/新建文本文档_1.txt");
        //        System.out.println(formatFileName(f.getName()));
        //        File nf = new File("D:/work/j2eeproject/filemsgtrans/tmp/pend/2011032816/新建文本文档_2.txt");
        //        f.renameTo(nf);
        //        nf.setLastModified(System.currentTimeMillis());
        File f = new File("d:\\1");
        File nf = new File("d:\\2\\1");
        System.out.println(nf.getParent());
        System.out.println(nf.isFile());
        //f.renameTo(nf);
    }
}
